#include "wifi_control.h"
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "esp_netif.h"
#include "esp_tls.h"
#include "esp_http_client.h"
#include "cJSON.h"

#include "def_board.h"

EventGroupHandle_t All_event_group;

static const char *TAG = "status_control";
static int retry_num = 0;


//-系统消息处理函数
extern void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    // 如果事件类型时WIFI事件，并且ID是STA_START，就开启WiFi连接
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
    {
        esp_wifi_connect();
    }
    // 如果事件类型时WIFI事件，并且ID是第一次连接失败
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
    {
        if (retry_num < ESP_MAXIMUM_RETRY)
        {
            esp_wifi_connect(); // 继续连接
            retry_num++;
            ESP_LOGI(TAG, "retry to connect to the AP");
        }
        else
        {
            // 测试次数超过MAX，给事件组发消息说连接失败
            xEventGroupSetBits(All_event_group, WIFI_FAIL_BIT);
        }
        ESP_LOGI(TAG, "connect to the AP fail");
    }
    // 系统接收到IP事件类型，ID为得到IP后发送消息
    else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
    {
        ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; // 触发函数传入的参数
        ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
        retry_num = 0;
        xEventGroupSetBits(All_event_group, WIFI_CONNECTED_BIT); // 给事件组发消息说连接成功
    }
}
